package com.shop.cereshop.agent.controller.order;

import com.shop.cereshop.agent.page.order.AgentOrderVO;
import com.shop.cereshop.agent.page.settlement.SettlementVO;
import com.shop.cereshop.agent.page.user.CereAgentUserVO;
import com.shop.cereshop.agent.param.order.OrderGetByIdDTO;
import com.shop.cereshop.agent.param.order.OrderPayDTO;
import com.shop.cereshop.agent.param.order.OrderSubmitDTO;
import com.shop.cereshop.agent.annotation.NoRepeatSubmit;
import com.shop.cereshop.agent.param.settlement.SettlementDTO;
import com.shop.cereshop.agent.service.order.AgentOrderService;
import com.shop.cereshop.commons.constant.IntegerEnum;
import com.shop.cereshop.commons.exception.CoBusinessException;
import com.shop.cereshop.commons.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @description:
 * @author lx
 * @date 2025/11/4 15:22
 * @version 1.0
 */
@RestController
@Api(value = "代理商订单模块", tags = "代理商订单模块")
@RequestMapping("/order")
@Slf4j(topic = "AgentOrderController")
public class AgentOrderController {
  @Resource
  private AgentOrderService agentOrderService;

  @ApiOperation(value = "商品结算查询")
  @PostMapping("/settlement")
  public Result<SettlementVO> getSettlement(@RequestBody SettlementDTO param, HttpServletRequest request) {
    CereAgentUserVO user = (CereAgentUserVO) request.getAttribute("user");
    if (user == null) {
      return Result.unauthorized();
    }
    SettlementVO settlement = agentOrderService.getSettlement(param, user.getAgentUserId());
    return Result.success(settlement);
  }

  @ApiOperation(value = "提交订单")
  @PostMapping("/submit")
  @NoRepeatSubmit
  public Result<Long> submitOrder(@RequestBody @Valid OrderSubmitDTO param, HttpServletRequest request)
      throws CoBusinessException, Exception {
    CereAgentUserVO user = (CereAgentUserVO) request.getAttribute("user");
    if (user == null) {
      return Result.unauthorized();
    }
    Long orderId = agentOrderService.submitOrder(param, user.getAgentUserId());
    return Result.success(orderId);
  }

  @ApiOperation(value = "代理商订单支付接口")
  @PostMapping("/agent/pay")
  @NoRepeatSubmit
  public Result<Void> agentPayOrder(@RequestBody @Valid OrderPayDTO param, HttpServletRequest request)
      throws CoBusinessException {
    CereAgentUserVO user = (CereAgentUserVO) request.getAttribute("user");
    if (user == null) {
      return Result.unauthorized();
    }
    agentOrderService.agentPayOrder(param, user.getAgentUserId());
    return Result.success();
  }

  @ApiOperation(value = "业务员订单支付接口")
  @PostMapping("/salesman/pay")
  @NoRepeatSubmit
  public Result<Void> salesmanPayOrder(@RequestBody @Valid OrderPayDTO param, HttpServletRequest request)
      throws CoBusinessException {
    CereAgentUserVO user = (CereAgentUserVO) request.getAttribute("user");
    if (user == null) {
      return Result.unauthorized();
    }
    // TODO: 实现业务员支付逻辑
    return Result.success();
  }

  @ApiOperation(value = "取消订单接口")
  @PostMapping("/cancel")
  public Result<Void> cancelOrder(@RequestBody OrderGetByIdDTO param, HttpServletRequest request)
      throws CoBusinessException {
    CereAgentUserVO user = (CereAgentUserVO) request.getAttribute("user");
    if (user == null) {
      return Result.unauthorized();
    }
    agentOrderService.cancelOrder(param, user.getAgentUserId());
    return Result.success();
  }

  @ApiOperation(value = "待支付订单列表查询接口")
  @GetMapping("/list")
  public Result<List<AgentOrderVO>> getOrderList(
      @RequestParam("page") @ApiParam(value = "页码", required = true) Integer page,
      @RequestParam("pageSize") @ApiParam(value = "每页大小", required = true) Integer pageSize,
      HttpServletRequest request) {
    // 获取当前登录用户
    CereAgentUserVO user = (CereAgentUserVO) request.getAttribute("user");
    if (user == null) {
      return Result.unauthorized();
    }

    try {
      // 根据用户角色类型查询订单
      // roleType: 1-代理商，2-业务员
      List<AgentOrderVO> orderList = new ArrayList<>();
      Integer roleType = user.getRoleType();

      if (Objects.equals(roleType, IntegerEnum.ROLE_TYPE_SALESMAN.getCode())) {
        // 业务员：只能查看自己的套餐订单（order_type=3）且状态为待付款（state=1）
        orderList = agentOrderService.getOrderListByUser(
            user.getAgentUserId(), IntegerEnum.ORDER_TYPE_PACKAGE.getCode(),
            IntegerEnum.AGENT_ORDER_STATE_WAIT_PAY.getCode(), page, pageSize);
      } else if (Objects.equals(roleType, IntegerEnum.ROLE_TYPE_AGENT.getCode())) {
        // 代理商：只能查看自己的普通订单（order_type=1）和代金券订单（order_type=2）且状态为待付款（state=1）
        List<AgentOrderVO> normalOrders = agentOrderService.getOrderListByUser(
            user.getAgentUserId(), IntegerEnum.ORDER_TYPE_NORMAL.getCode(),
            IntegerEnum.AGENT_ORDER_STATE_WAIT_PAY.getCode(), page, pageSize);
        List<AgentOrderVO> voucherOrders = agentOrderService.getOrderListByUser(
            user.getAgentUserId(), IntegerEnum.ORDER_TYPE_VOUCHER.getCode(),
            IntegerEnum.AGENT_ORDER_STATE_WAIT_PAY.getCode(), page, pageSize);
        if (normalOrders != null) {
          orderList.addAll(normalOrders);
        }
        if (voucherOrders != null) {
          orderList.addAll(voucherOrders);
        }
      } else {
        // 其他角色无权查询
        return Result.success(Collections.emptyList());
      }

      return Result.success(orderList);
    } catch (Exception e) {
      log.error("查询待支付订单列表失败，agentUserId:{}", user.getAgentUserId(), e);
      return Result.custom(com.shop.cereshop.commons.constant.CoReturnFormat.FAIL, "查询订单列表失败");
    }
  }

  @ApiOperation(value = "删除订单接口")
  @PostMapping("/delete")
  public Result<Void> deleteOrder(@RequestBody OrderGetByIdDTO param, HttpServletRequest request)
      throws CoBusinessException {
    CereAgentUserVO user = (CereAgentUserVO) request.getAttribute("user");
    if (user == null) {
      return Result.unauthorized();
    }
    agentOrderService.deleteOrder(param, user);
    return Result.success();
  }
}
